<?php

namespace App\Models;
use stdClass;

class PowerModel extends BaseModel {

	public function __construct() {
		parent::__construct();
		$this -> _table = "user";
	}

	public function getMenu($username) {
		$sql = "SELECT * FROM `user` INNER JOIN rolepower ON rolepower.RoleId = `user`.RoleId INNER JOIN power ON power.ID = rolepower.PowerId WHERE UserName = '" . $username . "' and ActionType = 'Menu'";
		$sth = $this -> _dbHandle -> prepare($sql);
		$sth -> execute();
		return $sth -> rowCount();
	}

	public function getCountRole($roleid) {
		$sql = "select power.ID,PowerName,power.ActionType FROM rolepower INNER JOIN power ON power.ID = PowerId WHERE RoleId = '" . $roleid . "'";
		$sth = $this -> _dbHandle -> prepare($sql);
		$sth -> execute();
		return $sth -> fetchAll();
	}

	public function SelectUserList($test) {
		$sth = $this -> _dbHandle -> prepare($test);
		$sth -> execute();
		return $sth -> fetchAll();
	}

	public function getCountw($sumw) {
		$sth = $this -> _dbHandle -> prepare($sumw);
		$sth -> execute();
		return $sth -> fetchAll();
	}

	public function powerGet($roleid) {
		$sql = "SELECT PowerName FROM rolepower INNER JOIN power ON rolepower.PowerId = power.ID WHERE RoleId='" + $roleid + "'";
		$sth = $this -> _dbHandle -> prepare($sql);
		$sth -> execute();
		return $sth -> fetchAll();
	}

	public function powerupdata($roleid, $powers) {
		//return count($powers);
		$arr = array();
		foreach ($powers as $key => $value) {
			$sql1 = "SELECT * FROM power INNER JOIN rolepower ON rolepower.PowerId = power.ID AND rolepower.RoleId = " + $roleid + " WHERE PowerName='" + $value + "'";
			$sql2 = "INSERT INTO rolepower(RoleId,PowerId) VALUES(" + $roleid + ",(SELECT power.ID FROM power WHERE PowerName = '" + $value + "' ))";
			if ($this -> query($sql1)) {
				$msg = array('message' => $value . '权限已存在', 'code' => 1);
			} else {
				if ($this -> query($sql2)) {
					$msg = array('message' => $value . '权限添加成功', 'code' => 0);
				} else {
					$msg = array('message' => $value . '权限添加失败', 'code' => 2);
				}
			}
			$arr[] = $msg;
		}
		return $arr;
	}

}
